<?php
/**
 * Created by PhpStorm.
 * User: ASUS
 * Date: 2018/7/8
 * Time: 16:18
 */

namespace YourApp\util;
use \GatewayWorker\Lib\Db;
use Model\CarModel;
use Workerman\Connection\AsyncTcpConnection;


/**
 * Class LocalInfo
 * @package YourApp\util
 * 位置信息汇报
 */
class Jt200
{
    public $status;
    public $status_parse;


    public $warn;
    public $warn_parse;

    public $lat;
    public $lng;
    public $height;
    public $speed;
    public $direction;
    public $date;

    public $ext;
    public $ext_parse;

    protected $body;
    protected $body_length;
    protected $has_ext=false;
    protected $ext_info_type=[
        '01',
        '02',
        '03',
        '11',
        '12',
        '13',
        '14',
        '15',
        '16',
        '17',
        '18',
        'E1',
        'E5',
        'ED',
        'EE',
        'F3',
        'F5',
        'F6',
        'BE'
    ];


    protected $materiel_type=[
        '无',
        '普通渣土',
        '砂石',
        '建筑废料'
    ];

    public function __construct($body_length,$body)
    {
        $this->body_length=$body_length;
        $this->body=$body;
        if($body_length>64){
            $this->has_ext=true;
        }
    }

    public function info(){
        $body=$this->body;
        //解析位置基本信息

        //报警标志
        $this->warn=substr($body,0,8);


        //状态
        $this->status=substr($body,8,8);

        //维度
        $this->lat=hexdec(substr($body,16,8))/1000000;

        //经度
        $this->lng=hexdec(substr($body,24,8))/1000000;

        //高程
        $this->height=hexdec(substr($body,32,4));

        //速度
        $this->speed=hexdec(substr($body,36,4))/10;

        //方向
        $this->direction=hexdec(substr($body,40,4));

        //时间
        $this->date='20'.substr($body,44,12);

        //车辆锁定
//        $this->lock=substr($body,56,2);

        //车辆限速
//        $this->limit_speed=substr($body,58,2);

        //限制举升
//        $this->limit_height=substr($body,60,2);

        //重车状态
//        $this->car_status=substr($body,62,2);

        //箱盖打开
//        $this->open_door=substr($body,64,2);

        //车厢升居
//        $this->up=substr($body,66,2);

        //维护模式
//        $this->fixed=substr($body,68,2);


        //附加信息
        if($this->has_ext){
            $this->ext=substr($body,68);
        }

    }

    public function parseStatus(){
        $tmp=base_convert('1'.$this->status,16,2);
        $tmp=array_reverse(str_split(substr($tmp,1)));
//        echo "\n".'status length is'.count($tmp).$this->status."\n";
//        $tmp=array_merge(array_slice($tmp,0,6),array_slice($tmp,10,3),array_slice($tmp,25,7));
        $status=['acc','location','lng','lat','run','encode','throttle',' switch','lock'];
//        $this->status_parse=array_combine($status,$tmp);
//        var_dump($tmp);
        $this->status_parse=$tmp;
    }

    public function parseWarn(){
        $tmp=base_convert('1'.$this->warn,16,2);
        $tmp=array_reverse(str_split(substr($tmp,1)));
//        $tmp=array_merge(array_slice($tmp,0,12),array_slice($tmp,18,11));
        $status=['warn','tried','over_speed',' alert','gnss_model','gnss_not_found','gnss_error','ele_press','ele_low',
            'lcd_error','tts_error','video_error','over_work','over_stop','in_out_area','in_out_line','diver_time_less_more',
            'leave_line','vss_error','oil_error','car_steal','illegal_fire','illegal_shifting'
        ];
//        $this->warn_parse=array_combine($status,$tmp);
//        var_dump($tmp);




        $this->warn_parse=$tmp;
    }
    public function parseExt(){
        $ext=strtoupper($this->ext);
        while(strlen($ext)){
            $ext_id=substr($ext,0,2);
            $length=base_convert(substr($ext,2,2),16,10)*2;
//            echo $ext_id.'=====>'.$length."\n";
            if(in_array($ext_id,$this->ext_info_type)){
                $info=substr($ext,4,$length);
//                echo $info."\n";
                switch ($ext_id){
                    case "01":
                    case "02":
                    case "03":
                    case "F3";
                        $after_parse=hexdec($info)/10;
                        break;
                    case "11":
                        $after_parse=hexdec($info);
                        if($after_parse!=0){
                            $area_or_line_id=substr($ext,2+$length,8);
                            $type=hexdec($area_or_line_id);
                            $after_parse=[$after_parse,$type];
                            $length+=4;
                        }
                        break;
                    case '12':
                        $type=hexdec(substr($info,0,2));
                        $area_or_line_id=hexdec(substr($info,2,8));
                        $direction=hexdec(substr($info,10,2));
                        $after_parse=[$type,$area_or_line_id,$direction];
                        break;
                    case '13':
                        $line_id=hexdec(substr($info,0,8));
                        $drive_time=hexdec(substr($info,8,8));
                        $result=hexdec(substr($info,16,8));
                        $after_parse=[$line_id,$drive_time,$result];
                        break;
                    case '14':
                    case '15':
                    case '16':
                    case '17':
                    case 'E1':
                    case 'E5':
                        $tmp=substr(base_convert('1'.$info,16,2),1);
                        $tmp=array_reverse(str_split($tmp));
                        $after_parse=$tmp;
                        break;
                    case '18':
                        $drive_type=substr($info,0,4);
                        $dec=hexdec($drive_type);
                        $drive_type=substr(base_convert('1'.$drive_type,16,2),1);
                        $drive_type=array_reverse(str_split($drive_type));
                        $level=substr($info,4,2);
                        $after_parse=[$drive_type,$level,$dec];
                        break;
                    case 'ED':
                    case 'EE':
                        $after_parse=hexdec($info);
                        break;
                    case 'F5':
                        $after_parse=trim(pack('H*',$info));
                        break;
                    case 'F6':
                        $total_km=substr($info,0,8);
                        $total_oil=substr($info,8,16);
                        $per_oil=hexdec(substr($info,16,2));
                        $use_oil_time=hexdec(substr($info,18,4));
                        $speed=hexdec(substr($info,22,4));
                        $rev=hexdec(substr($info,26,4));
                        $torque=hexdec(substr($info,30,8));
                        $voltage=hexdec(substr($info,38,4));
                        $brake=hexdec(substr($info,42,2));
                        $temperature=hexdec(substr($info,44,2));
                        $after_parse=compact('total_km','total_oil','per_oil','use_oil_time','speed','rev',
                            'torque','voltage','brake','temperature');
                        break;
                    case 'BE':
                        $after_parse=hexdec($info);

                }
                $this->ext_parse[$ext_id]=$after_parse;
            }
            $ext=substr($ext,4+$length);
        }
    }
    public function parse(){
        $this->info();
        $this->parseStatus();
        $this->parseWarn();
        $this->parseExt();
    }
    public function saveToDb($sim_card){
        $vtable=\YourApp\Config\Common::$VEHICLE;
        $db = Db::instance('ep');
        $register_sql="select * from `{$vtable}` where `sim_card_num`={$sim_card}";
        $row=$db->row($register_sql);


        $save_data=[
            'point_x'=>$this->lng,
            'point_y'=>$this->lat,
            'height'=>$this->height,
            'speed'=>$this->speed,
            'over_speed_warn'=>$this->warn_parse[1],
            'over_tried_warn'=>intval(($this->warn_parse[2] || (isset($this->ext_parse['E1']) && $this->ext_parse['E1'][22]))),
            'direction'=>$this->direction,
            'car_status'=>$this->status_parse[28],
            'is_open'=>$this->status_parse[29],
            'is_up'=>$this->status_parse[30],
            'sim_card'=>$sim_card,
            'time'=>strtotime($this->date),
            'is_limit_speed'=>$this->status_parse[26],
            'is_limit_up'=>$this->status_parse[27],
            'plate_num'=>$row['plate_num'],
            'vehicle_id'=>$row['id'],
            'area_poly_id'=>$row['area_id']
        ];

        $vehicle_point_table='vehicle_point_'.date('Y-m-d');
        $last_insert_id=$db->insert($vehicle_point_table)
            ->cols($save_data)
            ->query();

        $ext_data=[
            'location_info_id'=>$last_insert_id,
        ];
        if(isset($this->ext_parse['E1'])){
            $t=[
                'over_load'=>$this->ext_parse['E1'][18],
                'over_speed'=>$this->ext_parse['E1'][19],
                'illegal_put'=>$this->ext_parse['E1'][20],
                'is_unclose'=>$this->ext_parse['E1'][21],
                'illegal_driver'=>$this->ext_parse['E1'][22],
            ];
            $ext_data=array_merge($ext_data,$t);
        }
        if(isset($this->ext_parse['F3'])){
            $ext_data=array_merge($ext_data,['load'=>$this->ext_parse['F3']]);
        }
        if(isset($this->ext_parse['F5'])){
            $ext_data=array_merge($ext_data,['vin'=>$this->ext_parse['F5']]);
        }
        if(isset($this->ext_parse['F6'])){
            $ext_data=array_merge($ext_data,['speed'=>$this->ext_parse['F6']['speed']]);
        }
//        if(isset($this->ext_parse['BE'])){
//            $ext_data=array_merge($ext_data,['materiel'=>$this->ext_parse['BE']]);
//        }
        $ext_local='vehicle_location_extinfo_'.date('Y-m-d');
        $db->insert($ext_local)
            ->cols($ext_data)
            ->query();


        //插入报警信息
        $alarm=[];



        if($this->warn_parse[1]){
            //警告状态下的超速,超速行驶
            $alarm['type']=132;
        }
        //只有超速的时插入
        if(count($alarm)){
            //如果在5min内插入过相同alarm_type的就放弃插入
            //超速不应该漏掉,设置1min
            $before=date('Y-m-d H:i:s',strtotime('-1 min'));
            $sql="select count(`id`)  as `count` from `car_inout_alarm` where `create_time`>='{$before}' 
and `car_num`='{$row['plate_num']}' and alarm_type='{$alarm['type']}' ";
            $count=$db->query($sql);
            if(count($count)==0){
                $data=[
                    'area_id'=>1,
                    'car_num'=>$row['plate_num'],
                    'alarm_type'=>$alarm['type'],
                    'create_time'=>$this->date,
                    'deleted'=>0,
                    'status'=>6,
                    'alarm_level'=>3
                ];
                $key_id=$db->insert('car_inout_alarm')
                    ->cols($data)
                    ->query();

                //调用carmodel 保存flow 这里插入car_inout_alarm保存
                $car_model=new CarModel($row['plate_num'],null,null,null);
                $car_model->buildFlow($key_id,$alarm['type'],$this->speed,"{$this->lng},{$this->lat}");
            }
        }
    }
}